package com.aeye.mbr.upms.server.controller.manage;

import com.aeye.mbr.common.base.BaseController;
import com.aeye.mbr.common.result.BootstrapTableParams;
import com.aeye.mbr.common.ui.validator.LengthValidator;
import com.aeye.mbr.common.ui.validator.NotNullValidator;
import com.aeye.mbr.common.util.MD5Util;
import com.aeye.mbr.common.util.StringUtils;
import com.aeye.mbr.upms.common.constant.UpmsConstant;
import com.aeye.mbr.upms.common.constant.UpmsResult;
import com.aeye.mbr.upms.common.constant.UpmsResultConstant;
import com.aeye.mbr.upms.dao.model.*;
import com.aeye.mbr.upms.rpc.api.*;
import com.alibaba.fastjson.JSONArray;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户controller
 * Created by shuaeye.mbr on 2017/2/6.
 */
@Controller
@RequestMapping("/manage/user")
public class UpmsUserController extends BaseController {

    private static Logger _log = LoggerFactory.getLogger(UpmsUserController.class);

    @Autowired
    private UpmsUserService upmsUserService;

    @Autowired
    private UpmsRoleService upmsRoleService;

    @Autowired
    private UpmsOrganizationService upmsOrganizationService;

    @Autowired
    private UpmsUserOrganizationService upmsUserOrganizationService;

    @Autowired
    private UpmsUserRoleService upmsUserRoleService;

    @Autowired
    private UpmsUserPermissionService upmsUserPermissionService;

    @Autowired
    private UpmsApiService upmsApiService;

    @RequiresPermissions("upms:user:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/user/index.jsp";
    }

    @RequiresPermissions("upms:user:organization")
    @RequestMapping(value = "/organization/{id}", method = RequestMethod.GET)
    public String organization(@PathVariable("id") int id, ModelMap modelMap) {
        // 所有组织
        List<UpmsOrganization> upmsOrganizations = upmsOrganizationService.selectAll();
        // 用户拥有组织
        UpmsUserOrganization entity = new UpmsUserOrganization();
        entity.setUserId(id);
        List<UpmsUserOrganization> upmsUserOrganizations = upmsUserOrganizationService.select(entity);
        modelMap.put("upmsOrganizations", upmsOrganizations);
        modelMap.put("upmsUserOrganizations", upmsUserOrganizations);
        return "/manage/user/organization.jsp";
    }

    @RequiresPermissions("upms:user:organization")
    @RequestMapping(value = "/organization/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object organization(@PathVariable("id") int id, HttpServletRequest request) {
        String[] organizationIds = request.getParameterValues("organizationId");


        //验证顶级机构,不能跨顶级组织


        upmsUserOrganizationService.organization(organizationIds, id);
        return new UpmsResult(UpmsResultConstant.SUCCESS, "");
    }

    @RequiresPermissions("upms:user:role")
    @RequestMapping(value = "/role/{id}", method = RequestMethod.GET)
    public String role(@PathVariable("id") int id, ModelMap modelMap) {
        String currentUser = (String)SecurityUtils.getSubject().getPrincipal();

        // 所有角色
        UpmsRole upmsRole = new UpmsRole();
        if(StringUtils.isNotEmpty(currentUser) && !UpmsConstant.SUPER.equals(currentUser)){
            upmsRole.setCreateuser(currentUser);
        }
        List<UpmsRole> userCreatedUpmsRoles = upmsRoleService.select(upmsRole);
        List<UpmsRole> userOwnUpmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(upmsApiService.selectUpmsUserByUsername(currentUser).getUserId());
        UpmsUserRole entity = new UpmsUserRole();
        entity.setUserId(id);
        // 用户拥有角色
        List<UpmsUserRole> upmsUserRoles = upmsUserRoleService.select(entity);
        modelMap.put("upmsRoles", mergeRoles(userOwnUpmsRoles,userCreatedUpmsRoles));
        modelMap.put("upmsUserRoles", upmsUserRoles);
        return "/manage/user/role.jsp";
    }

    private Object mergeRoles(List<UpmsRole> userOwnUpmsRoles, List<UpmsRole> userCreatedUpmsRoles) {
        Map<Integer,UpmsRole> resultMap = new HashMap<Integer, UpmsRole>();
        if(!CollectionUtils.isEmpty(userOwnUpmsRoles)){
            for(UpmsRole role:userOwnUpmsRoles){
                resultMap.put(role.getRoleId(),role);
            }
        }
        if(!CollectionUtils.isEmpty(userCreatedUpmsRoles)){
            for(UpmsRole role:userCreatedUpmsRoles){
                resultMap.put(role.getRoleId(),role);
            }
        }
        List<UpmsRole> result = new ArrayList<>(resultMap.size());
        for(UpmsRole role:resultMap.values()){
            result.add(role) ;
        }
        return result;
    }

    @RequiresPermissions("upms:user:role")
    @RequestMapping(value = "/role/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object role(@PathVariable("id") int id, HttpServletRequest request) {
        String[] roleIds = request.getParameterValues("roleId");
        upmsUserRoleService.role(roleIds, id);
        return new UpmsResult(UpmsResultConstant.SUCCESS, "");
    }

    @RequiresPermissions("upms:user:permission")
    @RequestMapping(value = "/permission/{id}", method = RequestMethod.GET)
    public String permission(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsUser user = upmsUserService.selectByPrimaryKey(id);
        modelMap.put("user", user);
        return "/manage/user/permission.jsp";
    }

    @RequiresPermissions("upms:user:permission")
    @RequestMapping(value = "/permission/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object permission(@PathVariable("id") int id, HttpServletRequest request) {
        JSONArray datas = JSONArray.parseArray(request.getParameter("datas"));
        upmsUserPermissionService.permission(datas, id);
        return new UpmsResult(UpmsResultConstant.SUCCESS, datas.size());
    }

    @RequiresPermissions("upms:user:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            BootstrapTableParams params) {
        String user = (String)SecurityUtils.getSubject().getPrincipal();
        return upmsUserService.selectUpmsUserByParams(user,params);
    }

    @RequiresPermissions("upms:user:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create() {
        return "/manage/user/create.jsp";
    }

    @RequiresPermissions("upms:user:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Object create(UpmsUser upmsUser) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsUser.getUsername(), new LengthValidator(1, 20, "帐号"))
                .on(upmsUser.getPassword(), new LengthValidator(5, 32, "密码"))
                .on(upmsUser.getRealname(), new NotNullValidator("姓名"))
                .on(upmsUser.getPhone(), new NotNullValidator("手机号码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        long time = System.currentTimeMillis();
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        upmsUser.setSalt(salt);
        upmsUser.setPassword(MD5Util.MD5(upmsUser.getPassword() + upmsUser.getSalt()));
        //upmsUser.setCtime();
        String user = (String) SecurityUtils.getSubject().getPrincipal();
        upmsUser.setCreateuser(user);
        upmsUser = upmsUserService.createUser(upmsUser);
        if (null == upmsUser) {
            return new UpmsResult(UpmsResultConstant.FAILED, "帐号名已存在！");
        }
        _log.info("新增用户，主键：userId={}", upmsUser.getUserId());
        return new UpmsResult(UpmsResultConstant.SUCCESS, 1);
    }

    @RequiresPermissions("upms:user:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        int count = upmsUserService.deleteByPrimaryKeys(ids);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @RequiresPermissions("upms:user:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsUser user = upmsUserService.selectByPrimaryKey(id);
        modelMap.put("user", user);
        return "/manage/user/update.jsp";
    }

    @RequiresPermissions("upms:user:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") int id, UpmsUser upmsUser) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsUser.getUsername(), new LengthValidator(1, 20, "帐号"))
                .on(upmsUser.getRealname(), new NotNullValidator("姓名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        // 不允许直接改密码
        upmsUser.setPassword(null);
        upmsUser.setUserId(id);
        int count = upmsUserService.updateByPrimaryKeySelective(upmsUser);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }


    @RequiresPermissions("upms:user:update")
    @RequestMapping(value = "/update/{id}/password", method = RequestMethod.GET)
    public String updatePassword(@PathVariable("id") int id, ModelMap modelMap) {
        modelMap.put("userId", id);
        return "/manage/user/update-password.jsp";
    }

    @RequiresPermissions("upms:user:update")
    @RequestMapping(value = "/update/{id}/password", method = RequestMethod.POST)
    @ResponseBody
    public Object updatePassword(@PathVariable("id") int id, String password, String confirmPassword) {
        ComplexResult result = FluentValidator.checkAll()
                .on(password, new LengthValidator(5, 32, "密码"))
                .on(confirmPassword, new LengthValidator(5, 32, "确认密码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }

        if (!password.equals(confirmPassword)) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, "两次密码不一致！");
        }

        UpmsUser upmsUser = upmsUserService.selectByPrimaryKey(id);
        if (upmsUser == null) {
            return new UpmsResult(UpmsResultConstant.INVALID_USERNAME, "找不到用户！");
        }
        UpmsUser updateUser = new UpmsUser();
        updateUser.setUserId(id);
        updateUser.setPassword(MD5Util.MD5(password + upmsUser.getSalt()));
        int count = upmsUserService.updateByPrimaryKeySelective(updateUser);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }


}
